<template>
  <div class="chat-view">
    <el-card class="chat-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="chat-icon">
              <ChatDotRound />
            </el-icon>
            <span class="header-title">智能客服</span>
            <el-tag v-if="isOnline" type="success" size="small">在线</el-tag>
            <el-tag v-else type="info" size="small">离线</el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="clearAllMessages" type="text" size="small" :icon="Delete">
              清空对话
            </el-button>
          </div>
        </div>
      </template>

      <div class="chat-container">
        <!-- 对话区域 -->
        <div class="chat-dialog-area">
          <div class="dialog-header">
            <h4>对话记录</h4>
            <el-button @click="clearAllMessages" type="text" size="small" :icon="Delete">
              清空对话
            </el-button>
          </div>
          <div class="dialog-list" ref="dialogList">
            <!-- 欢迎消息 -->
            <div v-if="messages.length === 0" class="welcome-section">
              <div class="welcome-content">
                <el-icon class="welcome-icon">
                  <ChatDotRound />
                </el-icon>
                <h3>欢迎使用MES智能客服</h3>
                <p>我是您的专属MES系统AI助手，可以帮您解答关于物料管理、生产管理、质量管理、工艺管理等各个模块的问题</p>
                
                <!-- 快速问题 -->
                <div class="quick-questions">
                  <h4>常见问题：</h4>
                  <div class="question-grid">
                    <el-button 
                      v-for="question in quickQuestions" 
                      :key="question"
                      @click="sendQuickQuestion(question)"
                      type="primary"
                      plain
                      class="question-btn"
                    >
                      {{ question }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 对话列表 -->
            <div 
              v-for="(message, index) in messages" 
              :key="`message-${index}`" 
              class="dialog-item"
              :class="{ 'user-message': !message.isAI, 'ai-message': message.isAI }"
            >
              <div class="dialog-avatar">
                <el-avatar :size="32" :class="{ 'ai-avatar': message.isAI }">
                  <el-icon v-if="!message.isAI"><User /></el-icon>
                </el-avatar>
              </div>
              <div class="dialog-content">
                <div class="dialog-bubble">
                  <div class="dialog-text" v-html="formatMessage(message.message)"></div>
                  <div class="dialog-time">
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载指示器 -->
            <div v-if="isLoading" class="dialog-item ai-message">
              <div class="dialog-avatar">
                <el-avatar :size="32" class="ai-avatar">
                  
                </el-avatar>
              </div>
              <div class="dialog-content">
                <div class="dialog-bubble">
                  <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                    <span>AI正在思考中...</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              placeholder="请输入您的问题..."
              type="textarea"
              :rows="3"
              :autosize="{ minRows: 2, maxRows: 6 }"
              @keydown.enter.exact.prevent="sendMessage"
              @keydown.enter.shift.exact="inputMessage += '\n'"
              :disabled="isLoading"
              class="message-input"
            />
            <div class="input-actions">
              <el-button 
                @click="sendMessage" 
                type="primary" 
                :loading="isLoading"
                :disabled="!inputMessage.trim()"
                class="send-button"
              >
                <el-icon><Position /></el-icon>
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ChatDotRound,
  User,

  Position,
  Delete,
  ArrowDown
} from '@element-plus/icons-vue'
import ChatService, { type ChatResponse, type ChatSession } from '../api/chat'

// 响应式数据
const isOnline = ref(true)
const isLoading = ref(false)
const inputMessage = ref('')
const messages = ref<ChatResponse[]>([])
const currentSession = ref<ChatSession | null>(null)

// 快速问题
const quickQuestions = ref([
  '你好，我想了解一下MES系统',
  '物料管理功能',
  '生产管理模块',
  '质量管理流程',
  '工艺管理说明',
  '权限管理设置',
  '仓库管理功能',
  '系统使用帮助'
])

// 引用
const dialogList = ref<HTMLElement>()

// 方法
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  // 添加用户消息
  const userMsg: ChatResponse = {
    message: userMessage,
    sessionId: currentSession.value?.sessionId || '',
    timestamp: new Date().toISOString(),
    isAI: false
  }
  messages.value.push(userMsg)

  // 滚动到对话底部
  await nextTick()
  scrollDialogToBottom()

  // 发送到AI
  await sendToAI(userMessage)
}

const sendQuickQuestion = (question: string) => {
  inputMessage.value = question
  sendMessage()
}

const sendToAI = async (message: string) => {
  if (!currentSession.value) {
    await createNewSession()
  }

  isLoading.value = true

  try {
    const response = await ChatService.sendMessage({
      message,
      sessionId: currentSession.value!.sessionId
    })

    // 添加AI回复
    messages.value.push(response)

    // 滚动到对话底部
    await nextTick()
    scrollDialogToBottom()

  } catch (error: any) {
    console.error('发送消息失败:', error)
    
    // 获取详细错误信息
    let errorMessage = '抱歉，服务暂时不可用，请稍后再试。'
    if (error.response) {
      // 服务器响应了错误状态码
      errorMessage = `服务器错误 (${error.response.status}): ${error.response.data?.message || error.message}`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '无法连接到服务器，请检查网络连接或确认后端服务是否启动'
    } else {
      // 其他错误
      errorMessage = `请求错误: ${error.message}`
    }
    
    // 添加错误消息
    const errorMsg: ChatResponse = {
      message: errorMessage,
      sessionId: currentSession.value?.sessionId || '',
      timestamp: new Date().toISOString(),
      isAI: true
    }
    messages.value.push(errorMsg)

    ElMessage.error(`发送消息失败: ${errorMessage}`)
  } finally {
    isLoading.value = false
  }
}

const createNewSession = async () => {
  try {
    currentSession.value = await ChatService.createSession()
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
  }
}

const clearAllMessages = () => {
  messages.value = []
  ElMessage.success('对话记录已清空')
}

const scrollDialogToBottom = () => {
  if (dialogList.value) {
    dialogList.value.scrollTop = dialogList.value.scrollHeight
  }
}

const formatMessage = (message: string) => {
  // 消息格式化，支持换行和基本HTML标签
  return message
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/•/g, '&bull;')
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 生命周期
onMounted(async () => {
  await createNewSession()
})
</script>

<style scoped>
.chat-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.chat-card {
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions .el-button {
  color: #666;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.chat-dialog-area {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  max-height: 500px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.dialog-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.dialog-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 20px;
  max-height: 450px;
}

.welcome-section {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 400px;
}

.welcome-content {
  text-align: center;
  max-width: 500px;
}

.welcome-icon {
  font-size: 64px;
  color: #409eff;
  margin-bottom: 20px;
}

.welcome-content h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 24px;
}

.welcome-content p {
  margin: 0 0 30px 0;
  color: #666;
  font-size: 16px;
}

.quick-questions h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.question-btn {
  width: 100%;
  text-align: left;
  justify-content: flex-start;
  padding: 12px 16px;
  height: auto;
  white-space: normal;
  line-height: 1.4;
}

.message-wrapper {
  margin-bottom: 20px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.ai-message {
  display: flex;
  justify-content: flex-start;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 70%;
}

.user-message .message-item {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.ai-avatar {
  background: linear-gradient(135deg, #409eff, #67c23a);
}

.message-content {
  flex: 1;
}

.user-message .message-content {
  display: flex;
  justify-content: flex-end;
}

.message-bubble {
  background: white;
  padding: 16px 20px;
  border-radius: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  word-wrap: break-word;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
}

.ai-message .message-bubble {
  background: white;
  border: 1px solid #e4e7ed;
}

.ai-scrollable {
  max-height: 300px;
  overflow-y: auto;
  position: relative;
}

.ai-scrollable .message-text {
  max-height: 250px;
  overflow-y: auto;
  padding-right: 8px;
}

.message-text {
  line-height: 1.6;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: right;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.typing-indicator span:not(:last-child) {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #409eff;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

.typing-indicator span:last-child {
  color: #666;
  font-size: 12px;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-8px);
    opacity: 1;
  }
}

/* 用户问题区域 */
.user-questions-area {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  max-height: 150px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.questions-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.questions-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 20px;
  max-height: 100px;
}

.question-item {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-bottom: 6px;
}

.question-item:last-child {
  margin-bottom: 0;
}

.question-avatar {
  flex-shrink: 0;
}

.question-content {
  flex: 1;
}

.question-bubble {
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  padding: 6px 10px;
  border-radius: 8px;
  max-width: 100%;
}

.question-text {
  font-size: 13px;
  line-height: 1.4;
  color: #333;
  word-wrap: break-word;
}

.question-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

/* AI回复项样式 */
.ai-response-item {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-bottom: 6px;
}

.ai-response-item:last-child {
  margin-bottom: 0;
}

.ai-response-avatar {
  flex-shrink: 0;
}

.ai-response-content {
  flex: 1;
}

.ai-response-bubble {
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  padding: 6px 10px;
  border-radius: 8px;
  max-width: 100%;
}

.ai-response-text {
  font-size: 13px;
  line-height: 1.4;
  color: #333;
  word-wrap: break-word;
}

.ai-response-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

/* 对话项样式 */
.dialog-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
}

.dialog-item:last-child {
  margin-bottom: 0;
}

.dialog-item.user-message {
  flex-direction: row-reverse;
}

.dialog-item.user-message .dialog-content {
  display: flex;
  justify-content: flex-end;
}

.dialog-avatar {
  flex-shrink: 0;
}

.dialog-content {
  flex: 1;
  max-width: 70%;
}

.dialog-bubble {
  padding: 8px 12px;
  border-radius: 12px;
  max-width: 100%;
  word-wrap: break-word;
}

.user-message .dialog-bubble {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
}

.ai-message .dialog-bubble {
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  color: #333;
  min-height: auto;
  max-width: 100%;
}

.dialog-text {
  font-size: 13px;
  line-height: 1.6;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  max-height: none;
  overflow: visible;
}

.dialog-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.user-message .dialog-time {
  color: rgba(255, 255, 255, 0.8);
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.input-actions {
  display: flex;
  gap: 8px;
}

.send-button {
  height: 40px;
  padding: 0 20px;
}

/* 滚动条样式 */
.dialog-list::-webkit-scrollbar {
  width: 6px;
}

.dialog-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.dialog-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.dialog-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* AI消息滚动条样式 */
.ai-scrollable::-webkit-scrollbar {
  width: 6px;
}

.ai-scrollable::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.ai-scrollable::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.ai-scrollable::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.ai-scrollable .message-text::-webkit-scrollbar {
  width: 4px;
}

.ai-scrollable .message-text::-webkit-scrollbar-track {
  background: transparent;
}

.ai-scrollable .message-text::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 2px;
}

.ai-scrollable .message-text::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 滚动提示样式 */
.scroll-hint {
  position: absolute;
  bottom: 8px;
  right: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 8px;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0%, 100% { opacity: 0; }
  20%, 80% { opacity: 1; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-view {
    padding: 10px;
  }
  
  .chat-card {
    height: 90vh;
  }
  
  .chat-dialog-area {
    max-height: 300px;
  }
  
  .dialog-list {
    padding: 6px 12px;
    max-height: 250px;
  }
  
  .dialog-header {
    padding: 8px 12px;
  }
  
  .dialog-bubble {
    padding: 6px 10px;
  }
  
  .dialog-text {
    font-size: 12px;
  }
  
  .dialog-content {
    max-width: 85%;
  }
  
  .question-grid {
    grid-template-columns: 1fr;
  }
  
  .message-item {
    max-width: 85%;
  }
  
  .input-area {
    padding: 12px;
  }
  
  .input-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .input-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  /* 移动端AI消息滚动优化 */
  .ai-scrollable {
    max-height: 250px;
  }
  
  .ai-scrollable .message-text {
    max-height: 200px;
  }
}
</style>
